package com.ztgf.commodity.api.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ztgf.commodity.api.common.SysLogs;
import com.ztgf.commodity.models.dto.CommodityBrowseRecordingDTO;
import com.ztgf.commodity.models.service.ICommodityBrowseRecordingService;
import com.ztgf.common.utils.RequestUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class SysLogAspect {

    @DubboReference
    private ICommodityBrowseRecordingService commodityBrowseRecordingService;

    @Pointcut("@annotation(com.ztgf.commodity.api.common.SysLogs)")
    public void log() {
    }

    @AfterReturning("log()")
    public void after(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //请求参数，商品id
        String goodsId = request.getParameter("id");
        if (StringUtils.isBlank(goodsId)) {
            return;
        }
        //请求参数
        Object[] args = joinPoint.getArgs();
        CommodityBrowseRecordingDTO recordingDTO = new CommodityBrowseRecordingDTO();
        recordingDTO.setGoodsId(Long.valueOf(goodsId));
        recordingDTO.setIp(RequestUtil.getClientIp(request));
        recordingDTO.setUri(request.getRequestURI());
        recordingDTO.setActionName(getMethodSysLogsAnnotationValue(joinPoint));
        recordingDTO.setParams(JSONObject.toJSONString(args));
        commodityBrowseRecordingService.add(recordingDTO);
    }

    private String getMethodSysLogsAnnotationValue(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(SysLogs.class)) {
            // 获取方法上注解中表明的权限
            SysLogs sysLogs = method.getAnnotation(SysLogs.class);
            return sysLogs.value();
        } else if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            return apiOperation.value();
        }
        return "未知";
    }


}
